package com.stockprediction.analysis;
import libsvm.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

public class Anlysis {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        System.out.println("🔍 正在加载 SVM 模型...");
        svm_model model = svm.svm_load_model("svm_model.txt");
        if (model == null) {
            System.err.println("❌ 加载模型失败！");
            return;
        }
        System.out.println("✅ SVM 模型加载成功！");

        // **加载 TF-IDF 向量化器**
        TFIDFVectorizer vectorizer = TFIDFVectorizer.load("tfidf_vectorizer.bin");

        // **加载情感词典**
        String excelPath = "E:\\Personal\\pachong\\中文金融情感词典_姜富伟等(2020).xlsx";
        Set<String> negativeWords = SentimentDictionaryLoader.loadWords(excelPath, 1); // 负面词
        Set<String> positiveWords = SentimentDictionaryLoader.loadWords(excelPath, 2); // 正面词
        SentimentDictionary sentimentDictionary = new SentimentDictionary(positiveWords, negativeWords);

        // **启动用户输入预测**
        predictSingleNews(vectorizer, model, sentimentDictionary);
    }

    // 🎯 手动输入新闻进行预测
    public static void predictSingleNews(TFIDFVectorizer vectorizer, svm_model model, SentimentDictionary sentimentDictionary) {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("\n🔹 请输入一条新闻 (输入 'exit' 退出): ");
            String inputText = scanner.nextLine();
            if (inputText.equalsIgnoreCase("exit")) {
                System.out.println("👋 退出测试！");
                break;
            }

            // **1️⃣ 分词**
            String tokenizedText = ChineseTokenizer.tokenize(inputText);

            // **2️⃣ 计算情感词典得分**
            double dictScore = sentimentDictionary.getSentimentScore(tokenizedText);

            // **3️⃣ 转换为 TF-IDF 特征**
            double[] features = vectorizer.transform(tokenizedText);

            // **4️⃣ 进行 SVM 预测**
            double[] probEstimates = new double[2];
            int prediction = predict(model, features, probEstimates);

            double positiveProb = probEstimates[1];
            double negativeProb = probEstimates[0];

            // **5️⃣ 词典干预概率调整**
            double alpha = 0.008;  // 权重调整系数
            positiveProb += alpha * dictScore;
            negativeProb = 1 - positiveProb;  // 归一化

            // **6️⃣ 输出最终结果**
            double sentimentScore = positiveProb; // 直接用正面概率作为分数
            System.out.printf("📊 情感分数：%.2f（0 = 负面，1 = 正面）%n", sentimentScore);

        }
        scanner.close();
    }


    public static int predict(svm_model model, double[] features, double[] probEstimates) {
        List<svm_node> nodeList = new ArrayList<>();
        for (int i = 0; i < features.length; i++) {
            if (features[i] != 0) {  // 仅存储非零特征（稀疏优化）
                svm_node node = new svm_node();
                node.index = i + 1;
                node.value = features[i];
                nodeList.add(node);
            }
        }

        svm_node[] nodes = nodeList.toArray(new svm_node[0]);

        // 使用 SVM 进行预测并计算概率
        int prediction = (int) svm.svm_predict_probability(model, nodes, probEstimates);

        System.out.printf("📊 原始 SVM 预测 - 正面概率：%.2f | 负面概率：%.2f%n", probEstimates[1], probEstimates[0]);

        return prediction;
    }


}
